<template>
    
  <div class="data-analysis">
    <!-- 筛选条件 -->
   

    <div class="main-content">
      <div class="filter-section">
      <el-form :model="filterForm" class="filter-form" size="small">
        <div class="filter-row">
          <el-form-item label="年份">
            <el-select style="width: 110px;" v-model="filterForm.year" placeholder="请选择年份" clearable @change="handleYearChange">
              <el-option
                v-for="item in years"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="省份">
            <el-select style="width: 110px;" v-model="filterForm.province" placeholder="请选择省份" @change="handleProvinceChange">
              <el-option
                v-for="item in provinces"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市">
            <el-select style="width: 110px;" v-model="filterForm.city" placeholder="请选择城市" @change="handleCityChange">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区县">
            <el-select style="width: 110px;" v-model="filterForm.district" placeholder="请选择区县" clearable @change="handleDistrictChange" >
              <el-option
                v-for="item in districts"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="filter-row">
          <el-form-item label="我司竞争项目">
            <el-select 
              style="width: 180px;" 
              v-model="filterForm.project" 
              placeholder="请选择项目" 
              clearable 
              multiple 
              filterable 
              collapse-tags 
              collapse-tags-tooltip
              max-collapse-tags="2"
              @change="handleProjectChange">
              <el-option
                v-for="item in projects"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="竞品名称">
            <el-select 
              style="width: 100px;" 
              v-model="filterForm.competitor" 
              placeholder="请选择竞品" 
              clearable 
              multiple 
              filterable 
              collapse-tags 
              collapse-tags-tooltip
              max-collapse-tags="2"
              @change="handleCompetitorChange">
              <el-option
                v-for="item in competitors"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品类型" required>
            <el-select style="width: 100px;" v-model="filterForm.productType" placeholder="请选择产品类型" clearable @change="handleProductTypeChange" >
              <el-option
                v-for="item in productTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="竟品类型">
            <el-select v-model="selectedCity" placeholder="竟品类型" @change="handleProjectPropChange" clearable>
        <el-option
          v-for="item in typelist"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
          </el-form-item>
          <el-form-item label="项目输赢">
            <el-select v-model="selectedCity" placeholder="请选择项目输赢" @change="handleProjectPropChange" clearable>
        <el-option
          v-for="item in marlist"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <Taber 
      :province="getSelectedProvinceName()" 
      :city="getSelectedCityName()"
      :area="getSelectedDistrictName()"
      :our-project="getSelectedProjectName()"
      :competitor-count="competitorCount"
      :competitor-area="competitorArea"
      :competitor-sold-area="competitorSoldArea"
      :competitor-stock-area="competitorStockArea"
      :competitor-monthly-average="competitorMonthlyAverage">
    </Taber>

      <div class="chart-container">
                <!-- 图表区域 -->
        <div class="charts-section">
          <!-- 上排两个图表 -->
          <div class="chart-row-top">
            <!-- 去化价格对比折线图 -->
            <div class="chart-item">
              <div class="chart-title">去化价格对比</div>
              <div ref="priceChart" class="chart"></div>
            </div>

            <!-- 库存面积对比柱状图 -->
            <div class="chart-item">
              <div class="chart-title">库存面积对比</div>
              <div ref="inventoryChart" class="chart"></div>
            </div>
          </div>

          <!-- 下排单个图表 -->
          <div class="chart-row-bottom">
            <div class="chart-item">
              <div class="chart-title">去化面积对比</div>
              <div ref="salesAreaChart" class="chart"></div>
            </div>
            <div class="chart-item">
              <div class="chart-title">输赢对比</div>
              <div ref="winLoseChart" class="chart"></div>
            </div>
          </div>
        </div>

    
     
      </div>
    </div>
  </div>
</template>

<script>
import Taber from '@/components/taber.vue'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'DataAnalysis',
  components: {
    Taber
  },
  data() {
    return {
      competitorCount: null,
      competitorArea: null,
      competitorSoldArea: null,
      competitorStockArea: null,
      competitorMonthlyAverage: null,
      // 筛选条件
      filterForm: {
        year: '2025', // 默认选择今年
        province: '',
        city: '',
        district: '',
        competitor: [], // 改为数组支持多选
        project: [],    // 改为数组支持多选
        productType: ''
      },
      // 年份数据
      years: [
        // { value: '2021-2024', label: '2021年-2024年' },
        { value: '2025', label: '今年' }
      ],
      // 省份数据
      provinces: [
       
      ],
      // 城市数据
      cities: [],
      // 区县数据
      districts: [],
      // 竞品数据
      competitors: [],
      // 项目数据
      projects: [],
      // 产品类型数据
      productTypes: [
       
      ],
      // taber数据
      activeTab: 'total',
      // 排行榜数据
      margelist: [],
      marlist: [
        { value: '1', label: '赢' },
        { value: '2', label: '输' },
        { value: '3', label: '平' },
      ],
      // 图表实例
      priceChart: null,
      inventoryChart: null,
      salesAreaChart: null,
      winLoseChart: null,
      // resize防抖定时器
      resizeTimer: null,
      // 图表数据
      chartData: {
        price: {
          months: [],
          series: []
        },
        inventory: {
          months: [],
          series: []
        },
        salesArea: {
          months: [],
          series: []
        },
        winLose: {
          months: [],
          series: []
        }
      },
      // 图表数据状态跟踪
      chartDataStatus: {
        price: false,
        inventory: false,
        salesArea: false,
        winLose: false,
        allRequestsCompleted: 0
      }
    }
  },
    mounted() {
      this.getprovinces()
      this.getProductTypes() // 获取默认产品类型
      this.pronss()
      this.getCompetitorCount()
      this.getCompetitorArea()
      this.getCompetitorSoldArea()
      this.getCompetitorStockArea()
      this.getCompetitorMonthlyAverage()
      setTimeout(() => {
        this.updateAreaStats()
      }, 1000)
      this.$nextTick(() => {
        this.initCharts()
        // 初始化时先更新横坐标
        this.updateXAxisData()
        // 然后加载默认数据
      })
    },
  beforeDestroy() {
    if (this.priceChart) {
      this.priceChart.dispose()
    }
    if (this.inventoryChart) {
      this.inventoryChart.dispose()
    }
    if (this.salesAreaChart) {
      this.salesAreaChart.dispose()
    }
    if (this.winLoseChart) {
      this.winLoseChart.dispose()
    }
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer)
    }
    // window.removeEventListener('resize', this.handleResize)
  },
  methods: {
  

    // 获取友商数量
    getCompetitorCount(province = '', city = '', area = '', our_project = '') {
      //console.loglog('正在获取友商数量，省份:', province, '城市:', city, '区县:', area, '项目:', our_project)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      axios.get('/api/our-companies/project-count', { params }).then(res => {
        //console.loglog('友商数量API响应:', res.data)
        if (res.data && res.data.success && typeof res.data.count === 'number') {
          this.competitorCount = res.data.count
          //console.loglog('友商数量更新:', this.competitorCount)
        } else {
          //console.logwarn('友商数量API返回数据格式不正确:', res.data)
          this.competitorCount = 0
        }
      }).catch(error => {
        //console.logerror('获取友商数量失败：', error)
        this.competitorCount = 0
        if (error.response && error.response.status === 404) {
          //console.logwarn('友商数量接口不存在')
        } else {
          //this.$meaage.error('获取友商数量失败')
        }
      })
    },

    // 获取友商开盘面积
    getCompetitorArea(province = '', city = '', area = '', our_project = '') {
      //console.loglog('正在获取友商开盘面积，省份:', province, '城市:', city, '区县:', area, '项目:', our_project)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      axios.get('/api/our-companies/project-area', { params }).then(res => {
        //console.loglog('友商开盘面积API响应:', res.data)
        // 根据API文档，可能返回的字段名是 area 或其他名称
        if (res.data && res.data.success) {
          // 尝试多种可能的字段名
          const areaValue = res.data.area || res.data.competitor_area || res.data.total_area || 0
          if (typeof areaValue === 'number') {
            this.competitorArea = areaValue
            //console.loglog('友商开盘面积更新:', this.competitorArea)
          } else {
            //console.logwarn('友商开盘面积API返回数据格式不正确，area值:', areaValue)
            this.competitorArea = 0
          }
        } else {
          //console.logwarn('友商开盘面积API返回数据格式不正确:', res.data)
          this.competitorArea = 0
        }
        // 更新面积统计数据
        this.updateAreaStats()
      }).catch(error => {
        //console.logerror('获取友商开盘面积失败：', error)
        this.competitorArea = 0
        if (error.response && error.response.status === 404) {
          //console.logwarn('友商开盘面积接口不存在')
        } else {
          //this.$meaage.error('获取友商开盘面积失败')
        }
        // 更新面积统计数据
        this.updateAreaStats()
      })
    },

    // 获取友商去化面积
    getCompetitorSoldArea(province = '', city = '', area = '', our_project = '') {
      //console.loglog('正在获取友商去化面积，省份:', province, '城市:', city, '区县:', area, '项目:', our_project)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      axios.get('/api/our-companies/project-sold-area', { params }).then(res => {
        //console.loglog('友商去化面积API响应:', res.data)
        // 根据API文档，可能返回的字段名是 sold_area 或其他名称
        if (res.data && res.data.success) {
          // 尝试多种可能的字段名
          const soldAreaValue = res.data.sold_area || res.data.competitor_sold_area || res.data.total_sold_area || 0
          if (typeof soldAreaValue === 'number') {
            this.competitorSoldArea = soldAreaValue
            //console.loglog('友商去化面积更新:', this.competitorSoldArea)
          } else {
            //console.logwarn('友商去化面积API返回数据格式不正确，sold_area值:', soldAreaValue)
            this.competitorSoldArea = 0
          }
        } else {
          //console.logwarn('友商去化面积API返回数据格式不正确:', res.data)
          this.competitorSoldArea = 0
        }
        // 更新面积统计数据
        this.updateAreaStats()
      }).catch(error => {
        //console.logerror('获取友商去化面积失败：', error)
        this.competitorSoldArea = 0
        if (error.response && error.response.status === 404) {
          //console.logwarn('友商去化面积接口不存在')
        } else {
          //this.$meaage.error('获取友商去化面积失败')
        }
        // 更新面积统计数据
        this.updateAreaStats()
      })
    },

    // 获取竞品库存面积
    getCompetitorStockArea(province = '', city = '', area = '', our_project = '') {
      //console.loglog('正在获取竞品库存面积，省份:', province, '城市:', city, '区县:', area, '项目:', our_project)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      axios.get('/api/our-company-inventory/inventory-area', { params }).then(res => {
        //console.loglog('竞品库存面积API响应:', res.data)
        // 根据API文档，可能返回的字段名是 stock_area 或其他名称
        if (res.data && res.data.success) {
          // 尝试多种可能的字段名
          const stockAreaValue = res.data.total_inventory_area || res.data.competitor_stock_area || res.data.total_stock_area || 0
          if (typeof stockAreaValue === 'number') {
            this.competitorStockArea = stockAreaValue
            //console.loglog('竞品库存面积更新:', this.competitorStockArea)
          } else {
            //console.logwarn('竞品库存面积API返回数据格式不正确，stock_area值:', stockAreaValue)
            this.competitorStockArea = 0
          }
        } else {
          //console.logwarn('竞品库存面积API返回数据格式不正确:', res.data)
          this.competitorStockArea = 0
        }
        // 更新面积统计数据
        this.updateAreaStats()
      }).catch(error => {
        //console.logerror('获取竞品库存面积失败：', error)
        this.competitorStockArea = 0
        if (error.response && error.response.status === 404) {
          //console.logwarn('竞品库存面积接口不存在')
        } else {
          //this.$meaage.error('获取竞品库存面积失败')
        }
        // 更新面积统计数据
        this.updateAreaStats()
      })
    },

    // 获取竞品月均去化
    getCompetitorMonthlyAverage(province = '', city = '', area = '', our_project = '') {
      //console.loglog('正在获取竞品月均去化，省份:', province, '城市:', city, '区县:', area, '项目:', our_project)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      axios.get('/api/our-companies/project-sold-area', { params }).then(res => {
        //console.loglog('竞品去化面积API响应（用于计算月均）:', res.data)
        if (res.data && res.data.success) {
          // 尝试多种可能的字段名
          const soldAreaValue = res.data.sold_area || res.data.competitor_sold_area || res.data.total_sold_area || 0
          if (typeof soldAreaValue === 'number') {
            // 将去化面积除以6得到月均去化
            this.competitorMonthlyAverage = soldAreaValue / 6
            //console.loglog('竞品月均去化更新:', this.competitorMonthlyAverage, '(去化面积:', soldAreaValue, '/ 6)')
          } else {
            //console.logwarn('竞品去化面积API返回数据格式不正确，sold_area值:', soldAreaValue)
            this.competitorMonthlyAverage = 0
          }
        } else {
          //console.logwarn('竞品去化面积API返回数据格式不正确:', res.data)
          this.competitorMonthlyAverage = 0
        }
        // 更新面积统计数据
        this.updateAreaStats()
      }).catch(error => {
        //console.logerror('获取竞品月均去化失败：', error)
        this.competitorMonthlyAverage = 0
        if (error.response && error.response.status === 404) {
          //console.logwarn('竞品去化面积接口不存在')
        } else {
          //this.$meaage.error('获取竞品月均去化失败')
        }
        // 更新面积统计数据
        this.updateAreaStats()
      })
    },

    // 获取去化价格对比数据
    getPriceComparisonData(province = '', city = '', area = '', our_project = '', product_type = '') {
      //console.loglog('正在获取去化价格对比数据，省份:', province, '城市:', city, '区县:', area, '项目:', our_project, '产品类型:', product_type)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      if (product_type) params.product_type = product_type
      
      axios.get('/api/our-company-charts/price-comparison', { params }).then(res => {
        //console.loglog('去化价格对比API响应:', res.data)
        if (res.data && res.data.success && res.data.chart_data && res.data.chart_data.length > 0) {
          // 解析API返回的数据结构
          const chartData = res.data.chart_data
          
          // 提取所有月份作为横坐标
          const months = new Set()
          chartData.forEach(competitor => {
            if (competitor.data_points) {
              competitor.data_points.forEach(point => {
                if (point.date) {
                  // 将日期格式化为月份显示
                  const month = point.date.substring(5, 7) + '月'
                  months.add(month)
                }
              })
            }
          })
          const sortedMonths = Array.from(months).sort()
          
          // 更新图表数据
          this.chartData.price = {
            months: sortedMonths,
            series: chartData.map(competitor => ({
              name: competitor.competitor_name,
              data: this.formatPriceData(competitor.data_points, sortedMonths)
            }))
          }
          
          // 更新价格对比图表
          this.updatePriceChart()
          
          // 标记有数据
          this.chartDataStatus.price = true
        } else {
          //console.logwarn('去化价格对比API返回数据格式不正确:', res.data)
          this.clearPriceChart()
          this.chartDataStatus.price = false
        }
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
      }).catch(error => {
        //console.logerror('获取去化价格对比数据失败：', error)
        this.clearPriceChart()
        this.chartDataStatus.price = false
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
        
        if (error.response && error.response.status === 404) {
          //console.logwarn('去化价格对比接口不存在')
        } else {
          //this.$message.error('获取去化价格对比数据失败')
        }
      })
    },

    // 获取库存面积对比数据
    getInventoryComparisonData(province = '', city = '', area = '', our_project = '', product_type = '') {
      //console.loglog('正在获取库存面积对比数据，省份:', province, '城市:', city, '区县:', area, '项目:', our_project, '产品类型:', product_type)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      if (product_type) params.product_type = product_type
      
      axios.get('/api/our-company-charts/inventory-comparison', { params }).then(res => {
        //console.loglog('库存面积对比API响应:', res.data)
        if (res.data && res.data.success && res.data.chart_data && res.data.chart_data.length > 0) {
          // 解析API返回的数据结构
          const chartData = res.data.chart_data
          
          // 提取所有月份作为横坐标
          const months = new Set()
          chartData.forEach(competitor => {
            if (competitor.monthly_data) {
              competitor.monthly_data.forEach(point => {
                if (point.date) {
                  // 将日期格式化为月份显示
                  const month = point.date.substring(5, 7) + '月'
                  months.add(month)
                }
              })
            }
          })
          const sortedMonths = Array.from(months).sort()
          
          // 更新图表数据
          this.chartData.inventory = {
            months: sortedMonths,
            series: chartData.map(competitor => ({
              name: competitor.competitor_name,
              data: this.formatInventoryData(competitor.monthly_data, sortedMonths)
            }))
          }
          
          // 更新库存面积对比图表
          this.updateInventoryChart()
          
          // 标记有数据
          this.chartDataStatus.inventory = true
        } else {
          //console.logwarn('库存面积对比API返回数据格式不正确:', res.data)
          this.clearInventoryChart()
          this.chartDataStatus.inventory = false
        }
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
      }).catch(error => {
        //console.logerror('获取库存面积对比数据失败：', error)
        this.clearInventoryChart()
        this.chartDataStatus.inventory = false
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
        
        if (error.response && error.response.status === 404) {
          //console.logwarn('库存面积对比接口不存在')
        } else {
          //this.$message.error('获取库存面积对比数据失败')
        }
      })
    },

    // 获取去化面积对比数据
    getSoldAreaComparisonData(province = '', city = '', area = '', our_project = '', product_type = '') {
      //console.loglog('正在获取去化面积对比数据，省份:', province, '城市:', city, '区县:', area, '项目:', our_project, '产品类型:', product_type)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      if (product_type) params.product_type = product_type
      
      axios.get('/api/our-company-charts/sold-area-comparison', { params }).then(res => {
        //console.loglog('去化面积对比API响应:', res.data)
        if (res.data && res.data.success && res.data.chart_data && res.data.chart_data.length > 0) {
          // 解析API返回的数据结构
          const chartData = res.data.chart_data
          
          // 提取所有月份作为横坐标
          const months = new Set()
          chartData.forEach(competitor => {
            if (competitor.monthly_data) {
              competitor.monthly_data.forEach(point => {
                if (point.date) {
                  // 将日期格式化为月份显示
                  const month = point.date.substring(5, 7) + '月'
                  months.add(month)
                }
              })
            }
          })
          const sortedMonths = Array.from(months).sort()
          
          // 更新图表数据
          this.chartData.salesArea = {
            months: sortedMonths,
            series: chartData.map(competitor => ({
              name: competitor.competitor_name,
              data: this.formatSoldAreaData(competitor.monthly_data, sortedMonths)
            }))
          }
          
          // 更新去化面积对比图表
          this.updateSalesAreaChart()
          
          // 标记有数据
          this.chartDataStatus.salesArea = true
        } else {
          //console.logwarn('去化面积对比API返回数据格式不正确:', res.data)
          this.clearSalesAreaChart()
          this.chartDataStatus.salesArea = false
        }
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
      }).catch(error => {
        //console.logerror('获取去化面积对比数据失败：', error)
        this.clearSalesAreaChart()
        this.chartDataStatus.salesArea = false
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
        
        if (error.response && error.response.status === 404) {
          //console.logwarn('去化面积对比接口不存在')
        } else {
          //this.$message.error('获取去化面积对比数据失败')
        }
      })
    },

    // 获取输赢对比数据
    getWinLoseComparisonData(province = '', city = '', area = '', our_project = '', product_type = '') {
      //console.loglog('正在获取输赢对比数据，省份:', province, '城市:', city, '区县:', area, '项目:', our_project, '产品类型:', product_type)
      
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      if (our_project) params.our_project = our_project
      if (product_type) params.product_type = product_type
      
      // TODO: 替换为实际的API接口地址
      // 示例接口: '/api/our-company-charts/win-lose-comparison'
      axios.get('/api/our-company-charts/win-lose-comparison', { params }).then(res => {
        //console.loglog('输赢对比API响应:', res.data)
        if (res.data && res.data.success && res.data.chart_data && res.data.chart_data.length > 0) {
          // 解析API返回的数据结构
          const chartData = res.data.chart_data
          
          // 提取所有月份作为横坐标
          const months = new Set()
          chartData.forEach(competitor => {
            if (competitor.monthly_data) {
              competitor.monthly_data.forEach(point => {
                if (point.date) {
                  // 将日期格式化为月份显示
                  const month = point.date.substring(5, 7) + '月'
                  months.add(month)
                }
              })
            }
          })
          const sortedMonths = Array.from(months).sort()
          
          // 更新图表数据
          this.chartData.winLose = {
            months: sortedMonths,
            series: chartData.map(competitor => ({
              name: competitor.competitor_name,
              data: this.formatWinLoseData(competitor.monthly_data, sortedMonths)
            }))
          }
          
          // 更新输赢对比图表
          this.updateWinLoseChart()
          
          // 标记有数据
          this.chartDataStatus.winLose = true
        } else {
          //console.logwarn('输赢对比API返回数据格式不正确:', res.data)
          this.clearWinLoseChart()
          this.chartDataStatus.winLose = false
        }
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
      }).catch(error => {
        //console.logerror('获取输赢对比数据失败：', error)
        this.clearWinLoseChart()
        this.chartDataStatus.winLose = false
        
        // 增加完成计数并检查是否需要显示提示
        this.chartDataStatus.allRequestsCompleted++
        this.checkAllRequestsCompleted()
        
        if (error.response && error.response.status === 404) {
          //console.logwarn('输赢对比接口不存在')
        } else {
          //this.$message.error('获取输赢对比数据失败')
        }
      })
    },

    // 格式化价格数据
    formatPriceData(dataPoints, months) {
      if (!dataPoints || !Array.isArray(dataPoints)) {
        return new Array(months.length).fill(null)
      }
      
      const dataMap = {}
      dataPoints.forEach(point => {
        if (point.date && point.price !== undefined) {
          const month = point.date.substring(5, 7) + '月'
          dataMap[month] = point.price
        }
      })
      
      return months.map(month => dataMap[month] || null)
    },

    // 格式化库存面积数据
    formatInventoryData(monthlyData, months) {
      if (!monthlyData || !Array.isArray(monthlyData)) {
        return new Array(months.length).fill(null)
      }
      
      const dataMap = {}
      monthlyData.forEach(point => {
        if (point.date && point.inventory_area !== undefined) {
          const month = point.date.substring(5, 7) + '月'
          dataMap[month] = point.inventory_area
        }
      })
      
      return months.map(month => dataMap[month] || null)
    },

    // 格式化去化面积数据
    formatSoldAreaData(monthlyData, months) {
      if (!monthlyData || !Array.isArray(monthlyData)) {
        return new Array(months.length).fill(null)
      }
      
      const dataMap = {}
      monthlyData.forEach(point => {
        if (point.date && point.sold_area !== undefined) {
          const month = point.date.substring(5, 7) + '月'
          dataMap[month] = point.sold_area
        }
      })
      
      return months.map(month => dataMap[month] || null)
    },

    // 格式化输赢对比数据
    formatWinLoseData(monthlyData, months) {
      if (!monthlyData || !Array.isArray(monthlyData)) {
        return new Array(months.length).fill(null)
      }
      
      const dataMap = {}
      monthlyData.forEach(point => {
        if (point.date && point.win_lose_value !== undefined) {
          // 根据实际API返回的字段名调整，可能是 win_lose_value, win_lose, value 等
          const month = point.date.substring(5, 7) + '月'
          const value = point.win_lose_value || point.win_lose || point.value || 0
          dataMap[month] = value
        }
      })
      
      return months.map(month => dataMap[month] || null)
    },

    // 更新价格对比图表
    updatePriceChart() {
      if (this.priceChart && this.chartData.price) {
        const series = this.chartData.price.series ? this.chartData.price.series.map((item, index) => ({
          name: item.name,
          data: item.data,
          type: 'line',
          itemStyle: {
            color: this.getSeriesColor(index)
          },
          lineStyle: {
            width: this.getLineWidth()
          },
          symbol: 'circle',
          symbolSize: this.getSymbolSize()
        })) : []
        
        const priceOption = {
          xAxis: {
            data: this.chartData.price.months || []
          },
          legend: {
            data: series.map(s => s.name)
          },  
          series: series
        }
        this.priceChart.setOption(priceOption)
      }
    },

    // 更新库存面积对比图表
    updateInventoryChart() {
      if (this.inventoryChart && this.chartData.inventory) {
        const series = this.chartData.inventory.series ? this.chartData.inventory.series.map((item, index) => ({
          name: item.name,
          data: item.data,
          type: 'bar',
          barWidth: this.getBarWidth(),
          itemStyle: {
            color: this.getSeriesColor(index),
            borderRadius: [4, 4, 0, 0]
          }
        })) : []
        
        const inventoryOption = {
          xAxis: {
            data: this.chartData.inventory.months || []
          },
          legend: {
            data: series.map(s => s.name)
          },
          series: series
        }
        this.inventoryChart.setOption(inventoryOption)
      }
    },

    // 更新去化面积对比图表
    updateSalesAreaChart() {
      if (this.salesAreaChart && this.chartData.salesArea) {
        const series = this.chartData.salesArea.series ? this.chartData.salesArea.series.map((item, index) => ({
          name: item.name,
          data: item.data,
          type: 'bar',
          barWidth: this.getBarWidth(),
          itemStyle: {
            color: this.getSeriesColor(index),
            borderRadius: [4, 4, 0, 0]
          }
        })) : []
        
        const salesAreaOption = {
          xAxis: {
            data: this.chartData.salesArea.months || []
          },
          legend: {
            data: series.map(s => s.name)
          },
          series: series
        }
        this.salesAreaChart.setOption(salesAreaOption)
      }
    },

    // 更新输赢对比图表
    updateWinLoseChart() {
      if (this.winLoseChart && this.chartData.winLose) {
        const series = this.chartData.winLose.series ? this.chartData.winLose.series.map((item, index) => ({
          name: item.name,
          data: item.data,
          type: 'bar',
          barWidth: this.getBarWidth(),
          itemStyle: {
            color: this.getSeriesColor(index),
            borderRadius: [4, 4, 0, 0]
          }
        })) : []
        
        const winLoseOption = {
          xAxis: {
            data: this.chartData.winLose.months || []
          },
          legend: {
            data: series.map(s => s.name)
          },
          series: series
        }
        this.winLoseChart.setOption(winLoseOption)
      }
    },

    // 清空价格对比图表
    clearPriceChart() {
      if (this.priceChart) {
        const emptyOption = {
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(50,50,50,0.7)',
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: [],
            right: 10,
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: {
            ...this.getGridConfig(),
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: [],
            axisLabel: {
              fontSize: this.getAxisFontSize(),
              rotate: this.getAxisRotate()
            }
          },
          yAxis: {
            type: 'value',
            name: '去化价格',
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              formatter: '{value}',
              fontSize: this.getAxisFontSize()
            }
          },
          series: [],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: '',
              fontSize: 14,
              fill: '#999'
            }
          }
        }
        this.priceChart.setOption(emptyOption, true)
      }
    },

    // 清空库存面积对比图表
    clearInventoryChart() {
      if (this.inventoryChart) {
        const emptyOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50,50,50,0.7)',
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: [],
            right: 10,
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: {
            ...this.getGridConfig(),
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              interval: 0,
              rotate: this.getAxisRotate(),
              fontSize: this.getAxisFontSize()
            }
          },
          yAxis: {
            type: 'value',
            name: '库存面积',
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: '',
              fontSize: 14,
              fill: '#999'
            }
          }
        }
        this.inventoryChart.setOption(emptyOption, true)
      }
    },

    // 清空去化面积对比图表
    clearSalesAreaChart() {
      if (this.salesAreaChart) {
        const emptyOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50,50,50,0.7)',
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: [],
            right: 10,
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: {
            ...this.getGridConfig(),
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              interval: 0,
              rotate: this.getAxisRotate(),
              fontSize: this.getAxisFontSize()
            }
          },
          yAxis: {
            type: 'value',
            name: '去化面积(㎡)',
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: '',
              fontSize: 14,
              fill: '#999'
            }
          }
        }
        this.salesAreaChart.setOption(emptyOption, true)
      }
    },

    // 清空输赢对比图表
    clearWinLoseChart() {
      if (this.winLoseChart) {
        const emptyOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50,50,50,0.7)',
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: [],
            right: 10,
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: {
            ...this.getGridConfig(),
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
              interval: 0,
              rotate: this.getAxisRotate(),
              fontSize: this.getAxisFontSize()
            }
          },
          yAxis: {
            type: 'value',
            name: '数值',
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无数据',
              fontSize: 14,
              fill: '#999'
            }
          }
        }
        this.winLoseChart.setOption(emptyOption, true)
      }
    },

    // 加载所有图表数据
    loadAllChartData() {
      const province = this.filterForm.province || ''
      const city = this.filterForm.city || ''
      const district = this.filterForm.district || ''
      const projectArray = this.filterForm.project
      const project = Array.isArray(projectArray) ? projectArray.join(',') : projectArray
      const productType = this.filterForm.productType
      
      // 检查必要条件：项目和产品类型
      if (!Array.isArray(projectArray) || projectArray.length === 0) {
        //console.logwarn('请先选择我司项目')
        return
      }
      
      if (!productType) {
        //console.logwarn('请先选择产品类型')
        return
      }
      
      // 在加载新数据前先强制清空现有数据和图表显示，避免数据叠加和携带
      this.chartData = {
        price: { months: [], series: [] },
        inventory: { months: [], series: [] },
        salesArea: { months: [], series: [] },
        winLose: { months: [], series: [] }
      }
      
      // 立即清空图表显示，确保旧数据不会保留
      this.clearPriceChart()
      this.clearInventoryChart()
      this.clearSalesAreaChart()
      this.clearWinLoseChart()
      
      // 初始化数据状态跟踪
      this.chartDataStatus = {
        price: false,
        inventory: false,
        salesArea: false,
        winLose: false,
        allRequestsCompleted: 0
      }
      
      // 并行加载四个图表的数据，省市区作为可选筛选条件
      this.getPriceComparisonData(province, city, district, project, productType)
      this.getInventoryComparisonData(province, city, district, project, productType)
      this.getSoldAreaComparisonData(province, city, district, project, productType)
      this.getWinLoseComparisonData(province, city, district, project, productType)
    },
    updateAreaStats() {
      // 计算总面积，用于计算百分比
      const totalArea = this.competitorArea + this.competitorSoldArea + this.competitorStockArea
      
      // 构建面积统计数据
      this.currentAreaStats = []
      
      // 开盘面积 - 即使为0也显示
      this.currentAreaStats.push({
        name: '开盘面积',
        value: this.competitorArea || 0,
        percentage: totalArea > 0 ? Math.round((this.competitorArea / totalArea) * 100) : 0,
        color: '#409eff',
        isPrice: false
      })
      
      // 去化面积 - 即使为0也显示
      this.currentAreaStats.push({
        name: '去化面积',
        value: this.competitorSoldArea || 0,
        percentage: totalArea > 0 ? Math.round((this.competitorSoldArea / totalArea) * 100) : 0,
        color: '#67c23a',
        isPrice: false
      })
      
      // 库存面积 - 即使为0也显示
      this.currentAreaStats.push({
        name: '库存面积',
        value: this.competitorStockArea || 0,
        percentage: totalArea > 0 ? Math.round((this.competitorStockArea / totalArea) * 100) : 0,
        color: '#e6a23c',
        isPrice: false
      })
      
      // 月均去化（这个不是面积，但也显示在统计中）- 即使为0也显示
      this.currentAreaStats.push({
        name: '月均去化',
        value: this.competitorMonthlyAverage || 0,
        percentage: this.competitorMonthlyAverage > 0 ? 100 : 0, // 月均去化有值时显示为100%
        color: '#f56c6c',
        isPrice: false
      })
      
      //console.loglog('面积统计数据更新:', this.currentAreaStats)
    },
    getprovinces(){
        axios.get('/api/our-companies/provinces').then(res=>{
            this.provinces = res.data.provinces.map(item=>{
                return {
                    value: item,
                    label: item
                }
            })
        }).catch(error => {
            //console.logerror('获取省份数据失败:', error)
            //this.$message.error('获取省份数据失败')
        })
    },
    
    // 初始化图表
    initCharts() {
      this.priceChart = echarts.init(this.$refs.priceChart)
      this.setPriceChartOption()

      this.inventoryChart = echarts.init(this.$refs.inventoryChart)
      this.setInventoryChartOption()

      this.salesAreaChart = echarts.init(this.$refs.salesAreaChart)
      this.setSalesAreaChartOption()

      this.winLoseChart = echarts.init(this.$refs.winLoseChart)
      this.setWinLoseChartOption()

      window.addEventListener('resize', this.handleResize)
    },
    // 设置价格对比折线图配置
    setPriceChartOption() {
      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(50,50,50,0.7)',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          data: [], // 初始化为空，稍后通过updateCharts更新
          right: 10,
          textStyle: {
            fontSize: this.getLegendFontSize()
          }
        },
        grid: {
          ...this.getGridConfig(),
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [], // 初始化为空，稍后通过updateCharts更新
          axisLabel: {
            fontSize: this.getAxisFontSize(),
            rotate: this.getAxisRotate()
          }
        },
        yAxis: {
          type: 'value',
          name: '去化价格',
          nameTextStyle: {
            fontSize: this.getAxisFontSize()
          },
          axisLabel: {
            formatter: '{value}',
            fontSize: this.getAxisFontSize()
          }
        },
        series: [] // 初始化为空，稍后通过updateCharts更新
      }
      this.priceChart.setOption(option)
    },
    // 设置库存面积对比柱状图配置
    setInventoryChartOption() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(50,50,50,0.7)',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          data: [], // 初始化为空，稍后通过updateCharts更新
          right: 10,
          textStyle: {
            fontSize: this.getLegendFontSize()
          }
        },
        grid: {
          ...this.getGridConfig(),
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [], // 初始化为空，稍后通过updateCharts更新
          axisLabel: {
            interval: 0,
            rotate: this.getAxisRotate(),
            fontSize: this.getAxisFontSize()
          }
        },
        yAxis: {
          type: 'value',
          name: '库存面积',
          nameTextStyle: {
            fontSize: this.getAxisFontSize()
          },
          axisLabel: {
            fontSize: this.getAxisFontSize()
          }
        },
        series: [] // 初始化为空，稍后通过updateCharts更新
      }
      this.inventoryChart.setOption(option)
    },

    // 设置去化面积对比图表配置
    setSalesAreaChartOption() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(50,50,50,0.7)',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          data: [], // 初始化为空，稍后通过updateCharts更新
          right: 10,
          textStyle: {
            fontSize: this.getLegendFontSize()
          }
        },
        grid: {
          ...this.getGridConfig(),
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [], // 初始化为空，稍后通过updateCharts更新
          axisLabel: {
            interval: 0,
            rotate: this.getAxisRotate(),
            fontSize: this.getAxisFontSize()
          }
        },
        yAxis: {
          type: 'value',
          name: '去化面积(㎡)',
          nameTextStyle: {
            fontSize: this.getAxisFontSize()
          },
          axisLabel: {
            fontSize: this.getAxisFontSize()
          }
        },
        series: [] // 初始化为空，稍后通过updateCharts更新
      }
      this.salesAreaChart.setOption(option)
    },

    // 设置输赢对比柱状图配置
    setWinLoseChartOption() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(50,50,50,0.7)',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          data: [], // 初始化为空，稍后通过updateCharts更新
          right: 10,
          textStyle: {
            fontSize: this.getLegendFontSize()
          }
        },
        grid: {
          ...this.getGridConfig(),
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [], // 初始化为空，稍后通过updateCharts更新
          axisLabel: {
            interval: 0,
            rotate: this.getAxisRotate(),
            fontSize: this.getAxisFontSize()
          }
        },
        yAxis: {
          type: 'value',
          name: '数值',
          nameTextStyle: {
            fontSize: this.getAxisFontSize()
          },
          axisLabel: {
            fontSize: this.getAxisFontSize()
          }
        },
        series: [] // 初始化为空，稍后通过updateCharts更新
      }
      this.winLoseChart.setOption(option)
    },
    // 处理窗口大小改变
    handleResize() {
      // 使用防抖避免频繁触发
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer)
      }
      
      this.resizeTimer = setTimeout(() => {
        // 先调用resize方法让图表适应新尺寸
        this.priceChart && this.priceChart.resize()
        this.inventoryChart && this.inventoryChart.resize()
        this.salesAreaChart && this.salesAreaChart.resize()
        this.winLoseChart && this.winLoseChart.resize()
        
        // 然后更新配置以适应新的屏幕尺寸
        this.updateChartOptions()
      }, 150) // 增加防抖延时
    },

    // 新增：专门用于更新图表配置的方法
    updateChartOptions() {
      // 只更新必要的配置项，避免完全重建图表
      if (this.priceChart) {
        const option = {
          legend: {
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: this.getGridConfig(),
          xAxis: {
            axisLabel: {
              fontSize: this.getAxisFontSize(),
              rotate: this.getAxisRotate()
            }
          },
          yAxis: {
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [
            {
              lineStyle: {
                width: this.getLineWidth()
              },
              symbolSize: this.getSymbolSize()
            },
            {
              lineStyle: {
                width: this.getLineWidth()
              },
              symbolSize: this.getSymbolSize()
            }
          ]
        }
        this.priceChart.setOption(option, false, true) // 使用merge模式
      }

      if (this.inventoryChart) {
        const option = {
          legend: {
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: this.getGridConfig(),
          xAxis: {
            axisLabel: {
              fontSize: this.getAxisFontSize(),
              rotate: this.getAxisRotate()
            }
          },
          yAxis: {
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [
            { barWidth: this.getBarWidth() },
            { barWidth: this.getBarWidth() }
          ]
        }
        this.inventoryChart.setOption(option, false, true) // 使用merge模式
      }

      if (this.salesAreaChart) {
        const option = {
          legend: {
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: this.getGridConfig(),
          xAxis: {
            axisLabel: {
              fontSize: this.getAxisFontSize(),
              rotate: this.getAxisRotate()
            }
          },
          yAxis: {
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [
            { barWidth: this.getBarWidth() },
            { barWidth: this.getBarWidth() }
          ]
        }
        this.salesAreaChart.setOption(option, false, true) // 使用merge模式
      }

      if (this.winLoseChart) {
        const option = {
          legend: {
            textStyle: {
              fontSize: this.getLegendFontSize()
            }
          },
          grid: this.getGridConfig(),
          xAxis: {
            axisLabel: {
              fontSize: this.getAxisFontSize(),
              rotate: this.getAxisRotate()
            }
          },
          yAxis: {
            nameTextStyle: {
              fontSize: this.getAxisFontSize()
            },
            axisLabel: {
              fontSize: this.getAxisFontSize()
            }
          },
          series: [
            { barWidth: this.getBarWidth() },
            { barWidth: this.getBarWidth() }
          ]
        }
        this.winLoseChart.setOption(option, false, true) // 使用merge模式
      }
    },

    // 获取屏幕宽度
    getScreenWidth() {
      return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    },

    // 获取图例字体大小
    getLegendFontSize() {
      const width = this.getScreenWidth()
      if (width < 480) return 10
      if (width < 768) return 11
      if (width < 1024) return 12
      return 13
    },

    // 获取坐标轴字体大小
    getAxisFontSize() {
      const width = this.getScreenWidth()
      if (width < 480) return 9
      if (width < 768) return 10
      if (width < 1024) return 11
      return 12
    },

    // 获取坐标轴旋转角度
    getAxisRotate() {
      const width = this.getScreenWidth()
      if (width < 768) return 45
      return 0
    },

    // 获取网格顶部间距
    getGridTop() {
      const width = this.getScreenWidth()
      if (width < 480) return 40
      if (width < 768) return 45
      if (width < 1920) return 50
      return 60 // 大屏幕增加顶部间距
    },

    // 获取网格配置
    getGridConfig() {
      const width = this.getScreenWidth()
      const height = window.innerHeight || document.documentElement.clientHeight
      
      // 检测苹果设备
      const isApple = /Mac|iPhone|iPad|iPod/.test(navigator.userAgent)
      
      if (width < 480) {
        return { top: 40, left: '10%', right: '10%', bottom: '15%' }
      } else if (width < 768) {
        return { top: 45, left: '8%', right: '8%', bottom: '12%' }
      } else if (width < 1024) {
        return { top: 50, left: '6%', right: '6%', bottom: '10%' }
      } else if (width < 1440) {
        return { top: 50, left: '5%', right: '5%', bottom: '10%' }
      } else if (width < 1920) {
        return { top: 55, left: '4%', right: '4%', bottom: '8%' }
      } else {
        // 超大屏幕使用更保守的边距
        const leftRight = isApple ? '8%' : '6%'
        return { top: 60, left: leftRight, right: leftRight, bottom: '8%' }
      }
    },

    // 获取柱状图宽度
    getBarWidth() {
      const width = this.getScreenWidth()
      if (width < 480) return '15%'
      if (width < 768) return '18%'
      if (width < 1024) return '20%'
      return '25%'
    },

    // 获取折线图线宽
    getLineWidth() {
      const width = this.getScreenWidth()
      if (width < 768) return 1
      return 2
    },

    // 获取折线图标记点大小
    getSymbolSize() {
      const width = this.getScreenWidth()
      if (width < 480) return 3
      if (width < 768) return 4
      return 5
    },

    // 获取系列颜色
    getSeriesColor(index) {
      const colors = ['#67C23A', '#F56C6C', '#409EFF', '#E6A23C', '#909399', '#F7BA2A', '#FF9800', '#9C27B0']
      return colors[index % colors.length]
    },
    // 获取横坐标数据
    getXAxisData() {
      const { year } = this.filterForm
      
      if (!year) {
        // 年份未选择时返回空数组
        return []
      }
      
      if (year === '2021-2024') {
        // 历史年份范围
        return ['2021', '2022', '2023', '2024']
      } else if (year === '2025') {
        // 今年的月份，截止到当前月
        const currentMonth = new Date().getMonth() + 1 // getMonth()返回0-11，所以+1
        const months = []
        for (let i = 1; i <= currentMonth; i++) {
          months.push(`${i}月`)
        }
        return months
      }
      
      return []
    },

    // 获取数据
 

    // 验证筛选条件
 
    // 模拟API调用
  

    // 更新数据
    updateDataWithResponse(response) {
      // 更新数据卡片
   

      // 更新图表数据
      this.chartData.price = response.priceData
      this.chartData.inventory = response.inventoryData
      this.chartData.salesArea = response.salesAreaData

      // 更新图表
      this.updateCharts()
    },

    // 更新图表
    updateCharts() {
      // 使用新的单独图表更新函数
      this.updatePriceChart()
      this.updateInventoryChart()
      this.updateSalesAreaChart()
      this.updateWinLoseChart()
    },

    // 处理年份变化
    handleYearChange(value) {
      if (value) {
        // 年份变化时，立即更新横坐标
        this.updateXAxisData()
        
        // 如果其他条件都已选择，重新加载数据
        if (this.filterForm.productType) {
       
        } else {
          // 如果条件不完整，只清空数据但保持新的横坐标
          this.clearDataKeepXAxis()
        }
      } else {
        // 年份被清空，完全清空图表
        this.clearData()
      }
    },

    // 处理筛选
    handleFilter() {
      // 检查是否选择了产品类型
      if (!this.filterForm.productType) {
        //this.$message.warning('请先选择产品类型')
        return
      }
    
    },

    // 处理省份变化
    handleProvinceChange(value) {
      //console.loglog(value)
      this.filterForm.city = ''
      this.filterForm.district = ''
      this.filterForm.competitor = []
      this.filterForm.project = []
      this.filterForm.productType = ''
      this.districts = []
      this.competitors = []
      this.projects = []
      
      if (value) {
        this.getCities(value)
      } else {
        this.cities = []
      }
      
      // 清空数据显示，因为需要重新选择项目和产品类型
      this.clearData()
      // 更新Taber数据（显示当前省份的总体数据）
      this.updateTaberData()
    },

    // 处理城市变化
    handleCityChange(value) {
      this.filterForm.district = ''
      this.filterForm.competitor = []
      this.filterForm.project = []
      this.filterForm.productType = ''
      this.competitors = []
      this.projects = []
      
      if (value) {
        this.getDistricts(value)
      } else {
        this.districts = []
      }
      
      // 清空数据显示，因为需要重新选择项目和产品类型
      this.clearData()
      // 更新Taber数据（显示当前城市的总体数据）
      this.updateTaberData()
    },

    // 处理区县变化
    handleDistrictChange(value) {
      this.filterForm.competitor = []
      // 保持项目和产品类型选择，让用户可以继续使用
      // this.filterForm.project = []
      // this.filterForm.productType = ''
      this.competitors = []
      // this.projects = []
      
      if (value) {
        this.getCompetitors(value)
      }
      
      // 如果项目和产品类型都已选择，重新加载图表数据以应用新的区县筛选条件
      if (Array.isArray(this.filterForm.project) && this.filterForm.project.length > 0 && this.filterForm.productType) {
        this.loadAllChartData()
      } else {
        // 清空图表数据显示
        this.clearData()
      }
      
      // 更新Taber数据
      this.updateTaberData()
    },

    // 处理竞品变化
    handleCompetitorChange(value) {
      // 保持项目和产品类型选择
      // this.filterForm.project = ''
      // this.filterForm.productType = ''
      
      if (value && value.length > 0) {
        // this.getProjects(value)
      } else {
        // 如果没有选择竞品，不需要清空项目
        // this.projects = []
      }
      
      // 竞品选择变化时，Taber数据可能也需要更新（如果有项目选择的话）
      this.updateTaberData()
      
      // 如果项目和产品类型都已选择，重新加载图表数据
      if (Array.isArray(this.filterForm.project) && this.filterForm.project.length > 0 && this.filterForm.productType) {
        this.loadAllChartData()
      } else {
        // 清空图表数据显示
        this.clearData()
      }
    },  

    // 处理项目变化
    handleProjectChange(value) {
      this.filterForm.competitor = []
      // 不要清空产品类型，让用户可以保持已选择的产品类型
      // this.filterForm.productType = ''
      
      if (value && value.length > 0) {
        // 选择了项目，获取对应的竞品名称和产品类型
        // 对于多选项目，使用第一个项目来获取竞品名称和产品类型
        this.getCompetitorNames(value[0])
        this.getProductTypes(value[0])
        
        // 立即更新Taber数据，这样用户选择项目后就能看到卡片数据更新
        this.updateTaberData()
        
        // 如果产品类型已经选择，立即加载图表数据
        if (this.filterForm.productType) {
          this.loadAllChartData()
        }
      } else {
        // 清空了项目选择，需要重置所有筛选条件
        
        // 清空省市区的选择
        this.filterForm.province = ''
        this.filterForm.city = ''
        this.filterForm.district = ''
        
        // 清空相关数据
        this.cities = []
        this.districts = []
        this.competitors = []
        
        // 清空图表数据
        this.clearData()
        
        // 重新获取全量的我司竞争项目数据（不受地区限制）
        this.pronss()
        
        // 更新Taber数据（显示全部数据，不限定地区）
        this.updateTaberData()
      }
    },
    pronss(province = '', city = '', area = ''){
      //console.loglog('正在获取我司项目数据（全量或条件筛选），省份:', province, '城市:', city, '区县:', area)
      
      // 构建参数对象，只添加有值的参数
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (area) params.area = area
      
      axios.get(`/api/our-companies`, { params }).then(res=>{
        //console.loglog('我司项目数据API响应:', res.data)
        this.projects = res.data.our_projects.map(item=>{
          return {
            value: item,
            label: item
          }
        })
      }).catch(error => {
        //console.logerror('获取我司项目数据失败:', error)
        this.projects = []
      })
    },

    // 处理产品类型变化
    handleProductTypeChange(value) {
      if (value) {
        // 立即清空所有图表显示，避免数据携带
        this.clearData()
        
        // 选择了产品类型，检查是否有项目选择，然后加载图表数据
        const { project } = this.filterForm
        if (Array.isArray(project) && project.length > 0) {
          // 必要条件满足（项目+产品类型），加载图表数据，省市区作为可选筛选条件
          this.loadAllChartData()
        } else {
          // 项目未选择，提示用户
          //console.logwarn('请先选择我司项目')
          // 不清空数据，让用户保持当前选择
        }
      } else {
        // 清空了产品类型选择，清空数据显示
        this.clearData()
      }
    },

    // 更新横坐标数据
    updateXAxisData() {
      const xAxisData = this.getXAxisData()
      
      // 更新所有图表的横坐标
      if (this.priceChart) {
        this.priceChart.setOption({
          xAxis: {
            data: xAxisData
          }
        })
      }
      
      if (this.inventoryChart) {
        this.inventoryChart.setOption({
          xAxis: {
            data: xAxisData
          }
        })
      }
      
      if (this.salesAreaChart) {
        this.salesAreaChart.setOption({
          xAxis: {
            data: xAxisData
          }
        })
      }
      
      if (this.winLoseChart) {
        this.winLoseChart.setOption({
          xAxis: {
            data: xAxisData
          }
        })
      }
    },

    // 清空数据但保持横坐标
    clearDataKeepXAxis() {
      // 清空图表数据结构
      this.chartData.price = { months: this.getXAxisData(), series: [] }
      this.chartData.inventory = { months: this.getXAxisData(), series: [] }
      this.chartData.salesArea = { months: this.getXAxisData(), series: [] }
      this.chartData.winLose = { months: this.getXAxisData(), series: [] }
      
      // 更新图表显示
      this.updateCharts()
    },

    // 清空数据显示
    clearData() {
      // 清空图表数据结构
      this.chartData = {
        price: { months: [], series: [] },
        inventory: { months: [], series: [] },
        salesArea: { months: [], series: [] },
        winLose: { months: [], series: [] }
      }
      
      // 清空图表显示
      this.clearPriceChart()
      this.clearInventoryChart()
      this.clearSalesAreaChart()
      this.clearWinLoseChart()
    },

    // 获取城市列表
    getCities(province) {
      //console.loglog(province)
      axios.get(`/api/our-companies/cities?province=${province}`).then(res=>{
        this.cities = res.data.cities.map(item=>{
          return {
            value: item,
            label: item
          }
        })
      }).catch(error => {
        //console.logerror('获取城市数据失败:', error)
       
        this.cities = []
      })
    },

    // 获取区县列表
    getDistricts(city) {
     axios.get(`/api/our-companies/areas`,{
        params: {
          province: this.filterForm.province,
          city: city,
   
        }
     }).then(res=>{
        this.districts = res.data.areas.map(item=>{
          return {
            value: item,
            label: item
          }
        })
     }).catch(error => {
        //console.logerror('获取区县数据失败:', error)
       
        this.districts = []
     })
  
    },
          

    // 获取竞品列表
    getCompetitors(district = '', province = '', city = '') {
      //console.loglog('正在获取我司项目数据，省份:', province, '城市:', city, '区县:', district)
      
      // 构建参数对象，只添加有值的参数
      const params = {}
      
      // 使用传入的参数，如果没有传入则使用filterForm中的值
      const actualProvince = province || this.filterForm.province
      const actualCity = city || this.filterForm.city
      const actualDistrict = district || this.filterForm.district
      
      if (actualProvince) params.province = actualProvince
      if (actualCity) params.city = actualCity
      if (actualDistrict) params.area = actualDistrict
      
      axios.get(`/api/our-companies`, { params }).then(res=>{
        //console.loglog('我司项目数据API响应:', res.data)
        this.projects = res.data.our_projects.map(item=>{
          return {
            value: item,
            label: item
          }
        })
      }).catch(error => {
        //console.logerror('获取我司项目数据失败:', error)
        this.projects = []
      })
    },

    // 获取竞品名称列表（基于我司项目）
    getCompetitorNames(ourProject) {
      axios.get(`/api/our-companies/competitor-names`,{
        params: {
          province: this.filterForm.province,
          city: this.filterForm.city,
          area: this.filterForm.district,
          our_project: ourProject
        }
      }).then(res=>{
        this.competitors = res.data.competitor_names.map(item=>{
          return {
            value: item,
            label: item
          }
        })
      }).catch(error => {
        this.competitors = []
      })
    },
    getProductTypes(our_project = '') {
      const params = {}
      if (our_project) {
        params.our_project = our_project
      }
      
      axios.get(`/api/our-companies/product-types`, { params }).then(res=>{
        this.productTypes = [
          {value: '分层首层', label: '分层首层'},
          {value: '分层楼上', label: '分层楼上'},
          {value: '分栋', label: '分栋'},
          {value: '轻钢', label: '轻钢'},
          {value: '其他', label: '其他'}
        ]
      
      }).catch(error => {
        //console.logerror('获取产品类型失败:', error)
        this.productTypes = []
      })
    },
   
    // 获取进度条百分比
    getProgressPercentage(value) {
      // 如果没有rankingList数据，返回0
      if (!this.margelist || this.rankingList.length === 0) {
        return 0
      }
      const max = Math.max(...this.rankingList.map(item => item.value))
      return max > 0 ? (value / max) * 100 : 0
    },

    // 获取进度条颜色
    getProgressColor(index) {
      const colors = ['#f56c6c', '#e6a23c', '#67c23a', '#409eff', '#909399']
      return colors[index] || colors[colors.length - 1]
    },

    // 获取选中的省份名称
    getSelectedProvinceName() {
      const selected = this.provinces.find(item => item.value === this.filterForm.province)
      return selected ? selected.label : ''
    },

    // 获取选中的城市名称
    getSelectedCityName() {
      const selected = this.cities.find(item => item.value === this.filterForm.city)
      return selected ? selected.label : ''
    },

    // 获取选中的区县名称
    getSelectedDistrictName() {
      const selected = this.districts.find(item => item.value === this.filterForm.district)
      return selected ? selected.label : ''
    },

    // 获取选中的项目名称
    getSelectedProjectName() {
      if (Array.isArray(this.filterForm.project) && this.filterForm.project.length > 0) {
        const selectedProjects = this.projects.filter(item => this.filterForm.project.includes(item.value))
        if (selectedProjects.length > 0) {
          return selectedProjects.map(item => item.label).join(', ')
        }
      }
      return ''
    },

    // 更新Taber数据
    updateTaberData() {
      const province = this.filterForm.province
      const city = this.filterForm.city
      const area = this.filterForm.district
      const projectArray = this.filterForm.project
      const ourProject = Array.isArray(projectArray) ? projectArray.join(',') : projectArray

      // 省市区作为可选参数传递，如果为空则传空字符串
      const provinceParam = province || ''
      const cityParam = city || ''
      const areaParam = area || ''
      
      // 调用API获取数据 - 无论是否有项目选择都获取数据
      // 如果有项目选择，则获取特定项目的数据
      // 如果没有项目选择，则获取该地区的总体数据
      this.getCompetitorCount(provinceParam, cityParam, areaParam, ourProject)
      this.getCompetitorArea(provinceParam, cityParam, areaParam, ourProject)
      this.getCompetitorSoldArea(provinceParam, cityParam, areaParam, ourProject)
      this.getCompetitorStockArea(provinceParam, cityParam, areaParam, ourProject)
      this.getCompetitorMonthlyAverage(provinceParam, cityParam, areaParam, ourProject)
    },

    // 检查所有请求是否完成并显示提示
    checkAllRequestsCompleted() {
      // 确保所有三个请求都已完成
      if (this.chartDataStatus.allRequestsCompleted >= 3) {
        // 检查是否所有接口都没有数据
        if (!this.chartDataStatus.price && !this.chartDataStatus.inventory && !this.chartDataStatus.salesArea) {
          this.$message.warning('暂无竞品的该产品类型数据')
          this.clearData()
        }
        
        // 重置状态供下次使用
        this.chartDataStatus = {
          price: false,
          inventory: false,
          salesArea: false,
          allRequestsCompleted: 0
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import './css/dataanaly.css';

.filter-section {
  .filter-form {
    .filter-row {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 20px;
      margin-bottom: 16px;
      
      .el-form-item {
        margin-bottom: 0;
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-form-item__label {
          white-space: nowrap;
          flex-shrink: 0;
        }
      }
    }
  }
}

// 响应式调整
@media screen and (max-width: 1200px) {
  .filter-section {
    .filter-form {
      .filter-row {
        gap: 15px;
        
        .el-form-item {
          gap: 6px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .filter-section {
    .filter-form {
      .filter-row {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
        
        .el-form-item {
          flex-direction: column;
          align-items: stretch;
          gap: 4px;
          
          .el-form-item__label {
            align-self: flex-start;
          }
          
          .el-select {
            width: 100% !important;
          }
        }
      }
    }
  }
}

::v-deep .el-select {
  width: 100px;
}
</style>